
package sale

import (
    "time"
    "strings"
	"dhfshop/models"
	"github.com/astaxie/beego/orm"
)

//商品快照的原理：商品信息一修改就会生成一个版本的商品信息，用户拍下商品时就记录这个商品的版本号
type ItemSnapshot struct {
    Id           int64     `orm:"column(id);pk;auto" json:"id" form:"id"`                         /* 快照编号 */
	ItemId       int64     `orm:"column(item_id)" json:"item_id" form:"item_id"`                  /*商品编号*/
	SkuId        int64     `orm:"column(sku_id)" json:"sku_id" form:"sku_id"`                     /*商品SKU编号*/
	SnapshotKey  string    `orm:"column(snap_key)" json:"snap_key" form:"snap_key"`               /*快照编码: 商户编号+g商品编号+快照时间戳*/
	SellerId     int64     `orm:"column(seller_id)" json:"seller_id" form:"seller_id"`            /*卖家编号*/
	Title        string    `orm:"column(title)" json:"title" form:"title"`                        /*商品标题*/
	GoodsNo      string    `orm:"column(goods_no);null" json:"goods_no"`                          /*货号 */
	CategoryId   int64     `orm:"column(cat_id)" json:"cat_id" form:"cat_id"`                     /*分类编号*/
	CategoryName string    `orm:"column(category_name);null" json:"category_name" form:"category_name"` /**/
	Sku          string    `orm:"column(sku);null" json:"sku" form:"sku"`                               /*SKU*/
	Image        string    `orm:"column(image);null" json:"image" form:"image"`                         /*图片*/
    Price        float32   `orm:"column(price);digits(12);decimals(2)" json:"price" form:"price"`       /*销售价*/
	CreatedAt    time.Time `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"` 
}

func init() {
    orm.RegisterModel(new(ItemSnapshot))   
}

// 创建快照
func AddItemSnapshot(v *ItemSnapshot) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(v)
	return
}

// 更新快照
func UpdateItemSnapshot(v *ItemSnapshot) (id int64, err error) {
	o := models.GetDefaultDB()
	m := ItemSnapshot{Id: v.Id}
	if err = o.Read(&m); err == nil {
		if id, err = o.Update(v); err == nil {
		   return 
		}
	}
	return
}


//查询商品快照 
func GetItemSnapshot(query map[string]string)(snapShot *ItemSnapshot,err error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(ItemSnapshot))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)	
	}
	if err = qs.One(snapShot); err == nil {
		return snapShot, nil
	}
	return nil, err
}

